package com.lancoo.znbkxx.teacher.net

import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException


/**
 * Created by Dadong on 2020/5/15
 * Describe:
 */
class MoreBaseUrlInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        //获取原始的originalRequest
        val originalRequest: Request = chain.request()
        //获取老的url
        val oldUrl: HttpUrl = originalRequest.url
        //获取originalRequest的创建者builder
        val builder: Request.Builder = originalRequest.newBuilder()
        //获取头信息的集合如：manage,mdffx
        val urlNameList: List<String> =
            originalRequest.headers("urlname")
        return if (urlNameList.isNotEmpty()) {
            //删除原有配置中的值,就是namesAndValues集合里的值
            builder.removeHeader("urlname")
            //获取头信息中配置的value,如：manage或者mdffx
            val urlName = urlNameList[0]
            var baseURL: HttpUrl? = null
            //根据头信息中配置的value,来匹配新的base_url地址
            if ("platform" == urlName) {
//                baseURL = TEST_API.toHttpUrlOrNull()
            } else if ("base" == urlName) {
//                baseURL = PRODUCTION_API.toHttpUrlOrNull()
            }
            //重建新的HttpUrl，需要重新设置的url部分
            val newHttpUrl = oldUrl.newBuilder()
                .scheme(baseURL!!.scheme) //http协议如：http或者https
                .host(baseURL.host) //主机地址
                .port(baseURL.port) //端口
                .build()
            //获取处理后的新newRequest
            val newRequest: Request = builder.url(newHttpUrl).build()
            chain.proceed(newRequest)
        } else {
            chain.proceed(originalRequest)
        }
    }
}
